<template>
  <div class="login-by-qr mtop-20">
    <div class="msg-wrap">
      打开<a
        href="https://music.163.com/#/download"
        style="text-decoration: none; color: blue"
        target="_blank"
      >网易云手机端</a>扫码登录
    </div>
    <div class="img-wrap">
      <img :src="imgData" class="img img-h">
      <div class="btn-refresh pointer" @click="getQrKey" v-show="qrType === 800">
      <i class="el-icon-refresh-left"></i></div>
    </div>
    <div class="msg-wrap">状态：{{message}}</div>
  </div>
</template>
  
  <script>
import { getQrKey, createQr, checkQr } from "@/api/request";
export default {
  data() {
    return {
      key: "",
      imgData: "",
      qrType: "",
      message: "",
    };
  },
  created() {
    this.getQrKey();
  },
  beforeDestroy() {
    window.clearTimeout(this.timer);
  },
  methods: {
    // 获取二维码key
    async getQrKey() {
      const { data: res } = await getQrKey();
      if (res.code !== 200) return this.$message.error("获取验证码失败");
      this.key = res.data.unikey;
      this.createQr();
    },
    async createQr() {
      const { data: res } = await createQr(this.key);
      if (res.code !== 200) return this.$message.error("生成二维码失败");
      this.imgData = res.data.qrimg;
      this.checkQr();
    },
    async checkQr() {
      const {data:res} = await checkQr(this.key);
      console.log(res);
      this.qrType = res.code;
      this.message = res.message;
      if(res.code === 801 || res.code === 802){
        this.timer = window.setTimeout(() => {
          this.checkQr();
        },1000)
      } else if(res.code === 803){
        this.$message.success('登录成功');
        this.$router.push('/discover/personalrecom');
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login-by-qr{
  position: relative;
  .img-wrap{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    margin:  0 auto;
    .btn-refresh{
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: #ccc;
      opacity: 0.8;
      color: red;
      display: flex;
      justify-content: center;
      align-items: center;
      i{
        font-size: 30px;
      }
    }
  }
  .msg-wrap{
    text-align: center;
  }
}
</style>